<!--
 * @Description: 更新昵称页面
 * @Author: Kerwin
 * @Date: 2024-08-31 10:52:15
 * @LastEditTime: 2024-08-31 11:23:46
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="container">
    <hy-nav-bar title="修改昵称" v-if="!configStore.isWeChatBrowser"></hy-nav-bar>
    <u-input type="nickname" v-model="userStore.userInfo.nickname" />
    <view class="tips">
      好名字可以让你的朋友更容易记住你
    </view>
    <view class="saveBtn">
      <u-button type="success" @click="submit">保存</u-button>
      <view class="sync" v-if="!configStore.isWeChatBrowser"><text @click="syncWxInfo">同步微信昵称</text> <u-icon
          name='reload'></u-icon>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { userApi } from '@/api'
import { useUserStore, useConfigStore } from '@/store'

const userStore = useUserStore()
const configStore = useConfigStore()

async function submit() {
  console.log(userStore.userInfo.nickname)
  if (!userStore.userInfo.nickname) {
    uni.showToast({
      title: '昵称不能为空',
      icon: 'none'
    })
    return
  }
  uni.showLoading({ title: '修改中' })
  await userApi.userInfoUpdate({
    nickname: userStore.userInfo.nickname
  }).finally(() => {
    uni.hideLoading()
    uni.showToast({
      title: '修改成功',
      icon: 'none',
      success: () => {
        uni.navigateBack()
      }
    })
  })
  await userStore.getUserInfo()
}
function syncWxInfo() {
  uni.showModal({
    title: '提示',
    content: '确认更新为当前微信昵称？',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        const params = {
          nickname: userStore.userInfo?.phone?.toString().replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
        }
        if (userStore.wxUserInfoGetter?.nickname) {
          params.nickname = userStore.wxUserInfoGetter?.nickname
        }
        uni.showLoading({
          title: "用户昵称更新中"
        })
        await userApi.userInfoUpdate(params).finally(() => {
          uni.hideLoading()
        })
        await userStore.getUserInfo()
      }
    }
  })
}
onLoad((option) => { })
</script>


<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f7f7f7;
  padding: 30rpx;
  position: relative;

  .tips {
    font-size: 24rpx;
    color: #B0B0B0;
    margin-top: 20rpx;
  }

  .sync {
    text-align: center;
    margin: 20rpx 0 0 0;
    font-size: 24rpx;
    color: #19be6b;
  }

  .saveBtn {
    position: absolute;
    left: calc((100% - 680rpx) / 2);
    bottom: calc(40rpx + env(safe-area-inset-bottom));
    width: 680rpx;
  }

  :deep(.uni-input-wrapper) {
    border-bottom: 1rpx solid #606266;
  }

}
</style>
